// 用户 个人中心
import { doLogin, doLoginCode } from '@/api/user.js';
import { toLogin } from '@/utils/baseConfig';
import {
  setToken,
  getToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  getRedirectUri,
  removeRedirectUri
} from '@/utils/auth';
import Router from '../../router';
import { homeUrl } from '@/utils/baseConfig'

export default {
  state: {
    userInfo: getUserInfo(),
    token: getToken(),
  },
  getters: {},
  mutations: {
    setUserToken(state, payload) {
      state.token = payload;
      setToken(payload);
    },
    setUserInfo(state, payload) {
      state.userInfo = payload;
      setUserInfo(payload);
    },
  },
  actions: {
    // 登录
    async userLogin({ commit }, payload) {
      try {
        let resData = await doLogin(payload);
        commit('setUserInfo', resData);
        commit('setUserToken', resData.token);
        Router.replace('/login?redirect=' + window.location.href);
        return resData;
      } catch (error) {
        console.log(error);
      }
    },
    // 登录
    async userLoginCode({ commit }, payload) {
      try {
        let resData = await doLoginCode(payload);
        commit('setUserInfo', resData);
        commit('setUserToken', resData.token);
        console.log('login', resData)
        const isHaveUrl = getRedirectUri();
        removeRedirectUri();
        window.location.href = isHaveUrl ? isHaveUrl : homeUrl;
        return resData;
      } catch (error) {
        console.log(error);
      }
    },
    // 登录过期
    async userLoginOut({ commit }) {
      commit('setUserInfo', null);
      commit('setUserToken', null);
      removeToken();
      removeUserInfo();
      toLogin();
    },
    // 退出登录
    async userLoginOutToHom({ commit }) {
      console.log('Router', Router.history.current.path);
      const path = Router.history.current.path;
      if(path !== '/home') {
        Router.replace('/home');
      }
      setTimeout(() => {
        commit('setUserInfo', null);
        commit('setUserToken', null);
        removeToken();
        removeUserInfo();
      }, 500)
    },
  },
};
